package com.javasea.mq.ack.service.impl;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasea.mq.ack.common.Constants;
import com.javasea.mq.ack.entity.BrokerMessageLog;
import com.javasea.mq.ack.entity.Order;
import com.javasea.mq.ack.mapper.BrokerMessageLogMapper;
import com.javasea.mq.ack.mapper.OrderMapper;
import com.javasea.mq.ack.service.BrokerMessageLogService;
import com.javasea.mq.ack.service.OrderService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 *@ClassName BrokerMessageLogService
 *@Description TODO
 *@Author longxiaonan@163.com
 *@Date 2022/4/24 0024 18:37
 */
@Service
public class BrokerMessageLogServiceImpl extends ServiceImpl<BrokerMessageLogMapper, BrokerMessageLog> implements BrokerMessageLogService {
    @Override
    public List<BrokerMessageLog> query4StatusAndTimeoutMessage() {
        List<BrokerMessageLog> list = this.lambdaQuery().eq(BrokerMessageLog::getStatus, 0)
                .lt(BrokerMessageLog::getNextRetry, LocalDateTime.now()).list();
        return list;
    }

    @Override
    public void changeBrokerMessageLogStatus(Long messageId, String orderSendFailure, Date date) {
        /**
         * update broker_message_log bml
         *         set bml.status = #{status,jdbcType=VARCHAR},
         *         bml.update_time = #{updateTime, jdbcType=TIMESTAMP}
         *         where bml.message_id = #{messageId,jdbcType=VARCHAR}
         */
        this.lambdaUpdate().set(BrokerMessageLog::getUpdateTime, LocalDateTime.now())
                .set(BrokerMessageLog::getStatus, orderSendFailure).eq(BrokerMessageLog::getMessageId, messageId)
                .update();
    }

    @Override
    public void update4ReSend(Long messageId, Date date) {
        /**
         * update broker_message_log bml
         *         set bml.try_count = bml.try_count + 1,
         *         bml.update_time = #{updateTime, jdbcType=TIMESTAMP}
         *         where bml.message_id = #{messageId,jdbcType=VARCHAR}
         */
        BrokerMessageLog byId = this.getById(messageId);
        Integer tryCount = byId.getTryCount();
        this.lambdaUpdate().set(BrokerMessageLog::getUpdateTime, LocalDateTime.now())
                .set(BrokerMessageLog::getTryCount, tryCount + 1).eq(BrokerMessageLog::getMessageId, messageId)
                .update();
    }
}
